package com.sunbeam.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;

import com.sunbeam.dao.UserDao;
import com.sunbeam.domain.User;
import com.sunbeam.utils.XmlUtils;

/**
 * @Title: UserDao.java
 * @Package com.sunbeam.dao.impl
 * @Description: TODO
 * @author lyz lyzpoq_gmail_com
 * @date 2014/02/11 10:45:03
 * @version V1.0
 */
public class UserDaoImpl implements UserDao {

	/**
	 * 
	 * @Title: find
	 * @Description: TODO
	 * @param @param username
	 * @param @param password
	 * @param @return
	 * @return User
	 * @throws
	 */
	@Override
	public User find(String username,String password){
		try {
			Document document=XmlUtils.getDocument();
			Node node = document.selectSingleNode( "//user[@username='"+username+"'and @password='"+password+"']" );
			if(node==null){
				return null;
			}else{
				User user=new User();
				 
				 SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
				 Date birthday=sf.parse(node.valueOf( "@birthday" ));
				 user.setBirthday(birthday);
				 user.setEmail(node.valueOf( "@email" ));
				 user.setId(node.valueOf( "@id" ));
				 user.setUsername(node.valueOf( "@username" ));
				 user.setPassword(node.valueOf( "@password" ));
				 user.setNickname(node.valueOf( "@nickname" ));
				 return user;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 
	 * @Title: find
	 * @Description: TODO
	 * @param @param username
	 * @param @return
	 * @return boolean
	 * @throws
	 */
	@Override
	public boolean find(String username){
		try {
			Document document=XmlUtils.getDocument();
			Node node = document.selectSingleNode( "//user[@username='"+username+"']" );
			if(node==null){
				return false;
			}else{
				 return true;
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 
	 * @Title: add
	 * @Description: TODO
	 * @param @param user
	 * @return void
	 * @throws
	 */
	@Override
	public void add(User user){
		try {
			Document document=XmlUtils.getDocument();
			Element e=document.getRootElement().addElement("user");
			e.addAttribute("id",user.getId());
			e.addAttribute("username",user.getUsername());
			e.addAttribute("password",user.getPassword());
			
			SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
			e.addAttribute("birthday",user.getBirthday()==null?"":sf.format(user.getBirthday()));
			e.addAttribute("email",user.getEmail());
			e.addAttribute("nickname",user.getNickname());
			// 写入到xml
			XmlUtils.write2Xml(document);
			
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

